package mybatisplus.spring.boot.admin.common.aspect;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import mybatisplus.spring.boot.admin.common.base.BizException;
import mybatisplus.spring.boot.admin.common.base.JsonResVo;
import mybatisplus.spring.boot.admin.common.enums.ErrorEnum;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * <p>
 * 通用 Api Controller 全局异常处理
 * </p>
 */
@RestControllerAdvice
@Slf4j
public class UnionExceptionHandler {
    /**
     * <p>
     * 自定义 REST 业务异常
     * <p>
     *
     * @param e 异常类型
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public JsonResVo handleBadRequest(Exception e) {
        /*
         * 业务逻辑异常
         */
        if (e instanceof BizException) {
            log.error("Error: handleBadRequest BizException StackTrace:",e);
            BizException bizException = ((BizException) e);
            return JsonResVo.buildErrorResult(bizException.getCode(),bizException.getMessage());
        }

        /*
         * 参数校验异常
         */
        if (e instanceof MethodArgumentNotValidException) {
            log.error("Error: handleBadRequest MethodArgumentNotValidException StackTrace:",e);
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            if (null != bindingResult && bindingResult.hasErrors()) {
                List<Object> jsonList = new ArrayList<>();
                bindingResult.getFieldErrors().stream().forEach(fieldError -> {
                    Map<String, Object> jsonObject = new HashMap<>();
                    jsonObject.put("name", fieldError.getField());
                    jsonObject.put("msg", fieldError.getDefaultMessage());
                    jsonList.add(jsonObject);
                });
                return JsonResVo.buildErrorResult(ErrorEnum.ERROR_PARAM,jsonList);
            }
        }

        /**
         * 系统内部异常，打印异常栈
         */
        log.error("Error: handleBadRequest StackTrace:",e);
        return JsonResVo.buildErrorResult(ErrorEnum.SYSTEM_ERROR);

    }
}
